package com.jbit.utils;

import com.alibaba.fastjson.JSON;
import com.jbit.constance.JWTConstance;
import com.jbit.dto.DmUser;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class JwtUtils {
    /**
     * 生成jwt唯一id
     */
    private static String JWT_ID = UUID.randomUUID().toString();
    /**
     * 签发人
     */
    private static String ISSUER = "jbit";

    /*设置JWT加盐信息*/
    private static SecretKey generalKey() {
        String stringKey = JWTConstance.JWT_SECRET;
        byte[] encodeKey = Base64.getDecoder().decode(stringKey);
        SecretKey secretKey = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return secretKey;
    }

    public static String generalToken(DmUser user) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //生成密钥
        SecretKey secretKey = generalKey();

        Map claims = new HashMap();
        claims.put("user", JSON.toJSONString(user));
        //记录jwt生成时间
        long nowMills = System.currentTimeMillis();
//        System.out.println(nowMills);
        Date nowTime = new Date(nowMills);

        //设置jwt过期时间
        long expMills = nowMills + JWTConstance.EXP_TIME_LENGTH;
        Date expTime = new Date(expMills);

        //Token构造器 帮我们生成token
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(nowTime)//设置签发时间
                .setExpiration(expTime)//设置过期时间
                .signWith(signatureAlgorithm, secretKey)//设置token生成规则
                .setId(JWT_ID)      //设置jwtid唯一id
                .setIssuer(ISSUER)  //设置签发人
                .setSubject(user.getUserId().toString());    //设置面向用户,一般可以设置成用户的id,唯一标识

        return jwtBuilder.compact();
    }

    /**
     * 解析Token
     *
     * @param token
     * @return
     */
    public static DmUser parseToken(String token) {
        if (token != null && token.length() != 0) {
            SecretKey key = generalKey();
            String json = null;
            try {
                json = Jwts.
                        parser().
                        setSigningKey(key).
                        parseClaimsJws(token).
                        getBody().get("user").
                        toString();
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
            } catch (UnsupportedJwtException e) {
                e.printStackTrace();
            } catch (MalformedJwtException e) {
                e.printStackTrace();
            } catch (SignatureException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            if (json != null) {
                return JSON.parseObject(json, DmUser.class);
            } else {
                return null;
            }

        }
        return null;

    }

    /**
     * 解析Token
     *
     * @param token
     * @return
     */
    public static Claims parseTokenClaims(String token) {
        SecretKey key = generalKey();

        return Jwts.
                parser().
                setSigningKey(key).
                parseClaimsJws(token).
                getBody();
    }
}
